-- UIDpExplain
-- Created by chengb Sep/10/2015
-- dp说明界面

UIDpExplain = class("UIDpExplain", function()
    return cc.Layer:create();
end);

function UIDpExplain.create(areaId)
    return UIDpExplain.new(areaId);
end

-- 从哪个关卡开始无需显示dp额外信息
local LAST_AREA_ID = 6;

-- 特殊关卡id（喧嚣的海港）
local SPECIAL_AREA_ID = 10011;

-- 构造函数
function UIDpExplain:ctor(areaId)
    self:setName("UIDpExplain");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/achievement/DpExplain.csb");
    self:addChild(node);
    self.node = node;

    -- 记录关卡id
    self.areaId = areaId;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 重绘
function UIDpExplain:redraw()
    -- 设置标题
    local areaId = self.areaId;
    local title = DungeonAreaM.query(areaId, "name");
    local titleLabel = findChildByName(self.node, "CT/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(title);

    -- 设置描述
    local contentLabel = findChildByName(self.node, "CT/content");
    local requireDp = DungeonAreaM.query(areaId, "unlock_dp");
    local requireDpStr = string.format(getLocStr("blue_value"), requireDp);
    local curDpStr = "";
    local curDp = AchievementM.calcAreasCumulateDp();
    if curDp < requireDp then
        -- dp值不足时，显示红色
        curDpStr = string.format(getLocStr("red_value"), curDp);
    else
        curDpStr = string.format(getLocStr("blue_value"), curDp);
    end

    local desc = string.format(getLocStr("area_unlock_dp_desc"), requireDpStr, curDpStr);
    TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    contentLabel:getVirtualRenderer():setLineHeight(TextStyleM.TEXT_SIZE_SMALL + 5);
    contentLabel = applyString(contentLabel, desc);

    self.leftDescLabel = findChildByName(self.node, "CT/left_desc");
    self.rightDescLabel = findChildByName(self.node, "CT/right_desc");

    -- 设置额外描述
    self:redrawExtraDesc();

    local titleInitY = titleLabel:getPositionY();

    -- 自适应所有组件
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local bg = findChildByName(self.node, "CT/bg_frame");

    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { titleLabel, contentLabel, self.leftDescLabel, btnOk },
        { 1.5*AlignM.DEFAULT_GAP, 1.5*AlignM.DEFAULT_GAP, 1.0*AlignM.DEFAULT_GAP});

    -- 修正一下组件的位置
    self.rightDescLabel:setPositionY(self.leftDescLabel:getPositionY());

    AlignM.adaptSubBg(self.node, AlignM.BG_SIZE_NORMAL);
    -- local bg1 = findChildByName(self.node, "CT/bg1");
    -- local bg2 = findChildByName(self.node, "CT/bg2");
    -- local fixY, deltaY = math.modf(AlignM.BG_SIZE_NORMAL.height * (1 - bg:getScaleY()) / 2);

    -- if deltaY < 0.5 then
    --     fixY = fixY - 2;
    -- else
    --     fixY = fixY - 3;
    -- end

    -- bg1:setPositionY(bg1:getPositionY() - fixY);
    -- bg2:setPositionY(bg2:getPositionY() - fixY);
end

-- 设置额外描述
function UIDpExplain:redrawExtraDesc()
    local leftDescLabel = self.leftDescLabel;
    local rightDescLabel = self.rightDescLabel;

    local areaId = self.areaId;
    if areaId >= LAST_AREA_ID then
        -- 低语之森之后的关卡没有额外描述
        leftDescLabel:setVisible(false);
        rightDescLabel:setVisible(false);
        return;
    end

    leftDescLabel:setVisible(true);
    rightDescLabel:setVisible(true);

    local function getPreAreas()
        -- 获取该区域之前的所有关卡
        local areas = DungeonAreaM.getMainAreas();
        local ret = {};
        for _, id in pairs(table.keys(areas)) do
            if id < areaId then
                table.insert(ret, id);
            end
        end

        table.sort(ret);
        return ret;
    end

    local preAreas = getPreAreas();
    local leftStr = "";
    local rightStr = "";
    for _, id in pairs(preAreas) do
        local name    = DungeonAreaM.query(id, "name");
        local curDp   = AchievementM.calcCurDp(id);
        local totalDp = AchievementM.calcTotalDp(id);
        leftStr = leftStr .. name .. "\n";
        rightStr = rightStr .. string.format("%d/%d", curDp, totalDp) .. "\n";
    end

    -- 如果海贼港湾激活了，也要显示其dp信息
    if DungeonAreaM.isSubAreaUnlocked(ME.user, SPECIAL_AREA_ID) then
        local parentId = DungeonAreaM.getParentId(SPECIAL_AREA_ID)
        local name     = DungeonAreaM.query(parentId, "name");
        local curDp    = AchievementM.calcCurDp(parentId);
        local totalDp  = AchievementM.calcTotalDp(parentId);
        leftStr = leftStr .. name .. "\n";
        rightStr = rightStr .. string.format("%d/%d", curDp, totalDp) .. "\n";
    end

    TextStyleM.setTextStyle(rightDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);
    TextStyleM.setTextStyle(leftDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);
    self.leftDescLabel:setString(leftStr);
    self.rightDescLabel:setString(rightStr);

    -- 文本整体居中
    local gap = 30;
    local w = self.leftDescLabel:getContentSize().width + gap + self.rightDescLabel:getContentSize().width;
    self.leftDescLabel:setPositionX(-w/2);
    self.rightDescLabel:setPositionX(w/2);
end

-- 适配
function UIDpExplain:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIDpExplain:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIDpExplain 界面析构清理");
            EventMgr.removeAll("UIDpExplain");
        end
    end);
end

-- 注册点击事件
function UIDpExplain:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIDpExplain");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 如果dp值足够，则领取奖励
            if DungeonAreaM.isDpEnoughToUnlock(self.areaId) then
                Operation.cmd_take_area_unlock_bonus(self.areaId);
            else
                alert(getLocStr("dp_not_enough"));
            end

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIDpExplain");
        end
    end
    btnOk:addTouchEventListener(onOkClick);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    if DungeonAreaM.isDpEnoughToUnlock(self.areaId) then
        btnOk:setTitleText(getLocStr("btn_text_unlock"));
    else
        btnOk:setTitleText(getLocStr("btn_text_ok"));
    end
end